package com.jf.cloud.service.sysmanager.remote.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jf.cloud.service.sysmanager.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.RegexValidUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.common.util.TokenUtil;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.constant.sms.SmsConstant;
import com.jf.cloud.service.sysmanager.dao.IPubgOperateLogService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserLoginBandingService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserService;
import com.jf.cloud.service.sysmanager.dao.ISmsService;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

@Controller
@RequestMapping("/appLogin")
public class AppLoginController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(AppLoginController.class);

	@Resource
	private IPubgUserService pubgUserService;
	
	@Resource
	private TokenHandler tokenHandler;
	
	/**
	 * 短信相关服务
	 */
	@Resource
	private ISmsService smsService;
	
	@Resource
	private IPubgOperateLogService pubgOperateLogService;
	
	@Resource
	private IPubgUserLoginBandingService pubgUserLoginBandingService;
	
	@Value("${spring.profiles.active}")
	private String active;
	
	/**
	 * 前台短信登陆
	 * 
	 * @author 朱建文 创建时间：2018年3月31日 下午4:20:40
	 */
	@ResponseBody
	@RequestMapping("/smsLogin")
	public Result<Map<String, Object>> smsLogin(HttpServletRequest request, HttpServletResponse response) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("登陆失败");
		try {
			
			String userAccount = getParamValueString(request, "userName");
			if (StringUtil.isNull(userAccount)) {
				result.setMessage("手机号为空");
				return result;
			}
			if (!RegexValidUtil.compile(RegexValidUtil.mobile, userAccount)) {
				result.setMessage("手机号格式错误！");
				return result;
			}
			
			// 注册来源  10：Android  20：IOS	30:小程序
			Integer regFrom = getParamValueInteger(request, "regFrom", 10);
			
			// 手机短信验证码验证
			String rs = "";
			String mobileCaptcha = getParamValueString(request, "mobileCaptcha", ""); // 手机验证码
			try {
				
				// 测试站、特殊号、小程序不验证 短信验证码  
				if ("test".equals(active) || "17000000000".equals(userAccount)) {
					rs = "0";
				} else {
					rs = smsService.checkSMS(null, userAccount, SmsConstant.USER_PHONE_MODEL_TYPE_100, mobileCaptcha);
				}
			} catch (Exception e) {
				log.error("手机注册短信验证码有误", e);
			}
			
			if (!"0".equals(rs)) {
				log.error("手机验证码错误：" + rs);
				result.setMessage(rs);
				return result; // 手机验证码错误
			}
			
			// 查询是否新用户
			Query query = new Query();
			query.put("USER_ACCOUNT", userAccount);
			List<PubgUser> pubgUserList = pubgUserService.findList(query);
			if (pubgUserList != null && pubgUserList.size() > 1) {
				result.setMessage("帐号存在多个，请联系管理员");
				return result;
			}
			
			// 获取登陆者的IP
			String regIp = getIp(request);
			log.info("client ip:" + regIp);
			
			PubgUser pubgUser = null;
			if (pubgUserList == null || pubgUserList.isEmpty()) {
				log.info("新账号登录！");
				
				pubgUser = new PubgUser();
				pubgUser.setUserAccount(userAccount);
				pubgUser.setUserRole(UserConstant.USER_ROLE_10.getId());
				pubgUser.setRegFrom(regFrom);
				pubgUser.setRegIp(regIp);
				pubgUser.setRegTime(DateUtil.getCurrentDateTime());
				pubgUser.setInfoCompleteFlag(0);
				pubgUser.setBalance(0.0);
				pubgUser.setMatchAmount(0);
				pubgUser.setWinAmount(0);
				pubgUser.setWinSum(0.0);
				pubgUser.setRealNameFlag(0);
				pubgUser = pubgUserService.saveObj(pubgUser);
				
				// 插入注册记录
				pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), UserConstant.USER_OPT_TYPE_10.getId().longValue(), UserConstant.USER_OPT_TYPE_10.getName());
			}
			
			if (pubgUser == null) {
				pubgUser = pubgUserList.get(0);
			}
			
			// 更新用户的注册IP（有部分IP为空，需要更新下）
			this.pubgUserService.updaeRegIp(pubgUser.getRowId(), regIp);
			
			// 插入登陆记录
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), UserConstant.USER_OPT_TYPE_20.getId().longValue(), UserConstant.USER_OPT_TYPE_20.getName());
			
			// 把登录成功后token保存
			String token = TokenUtil.buildToken();
			tokenHandler.putToken(token, pubgUser.getRowId() + "", pubgUser.getRowId() + "");
			pubgUser.setToken(token);
			
			// 更新验证码状态
			smsService.updateUserPhoneYzmState(null, userAccount, SmsConstant.USER_PHONE_MODEL_TYPE_100);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("token", token);
			data.put("rowId", pubgUser.getRowId());
			data.put("userAccount", pubgUser.getUserAccount().substring(0, 3) + "****" + pubgUser.getUserAccount().substring(8));
			data.put("nickname", pubgUser.getNickname() == null ? "" : pubgUser.getNickname());
			data.put("nicknameInitial", pubgUser.getNicknameInitial() == null ? "" : pubgUser.getNicknameInitial());
			data.put("gameRole", pubgUser.getGameRole() == null ? "" : pubgUser.getGameRole());
			data.put("linkQq", pubgUser.getLinkQq() == null ? "" : pubgUser.getLinkQq());
			data.put("balance", pubgUser.getBalance() == null ? 0 : pubgUser.getBalance());
			data.put("photo", pubgUser.getPhoto() == null ? "" : pubgUser.getPhoto());
			data.put("userRole", pubgUser.getUserRole());
			data.put("infoCompleteFlag", pubgUser.getInfoCompleteFlag() == null ? 0 : pubgUser.getInfoCompleteFlag());
			
			result.setCode(0);
			result.setData(data);
			result.setMessage("登陆成功");
		} catch (Exception e) {
			log.error("***************用户登录出错了", e);
		}
		return result;
	}
	
	/**
	 * 第三方登陆
	 * 
	 * @author 朱建文 创建时间：2018年5月9日 下午1:11:35
	 */
	@ResponseBody
	@RequestMapping("/thirdLogin")
	public Result<Map<String, Object>> thirdLogin(HttpServletRequest request, HttpServletResponse response) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("登陆失败");
		try {
			
			String userAccount = getParamValueString(request, "userName");
			if (StringUtil.isNull(userAccount)) {
				result.setMessage("手机号为空");
				return result;
			}
			if (!RegexValidUtil.compile(RegexValidUtil.mobile, userAccount)) {
				result.setMessage("手机号格式错误！");
				return result;
			}
			
			// 登陆方式	20:QQ	30:微信	 40:小程序
			int loginWay = getParamValueInteger(request, "loginWay", 10); 
			if (loginWay != 20 && loginWay != 30 && loginWay != 40) {
				result.setMessage("loginWay不合法！");
				return result;
			}
			
			String openId = getParamValueString(request, "openId");
			if (StringUtil.isNull(openId)) {
				result.setMessage("openId为空！");
				return result;
			}
			
			String nickname = getParamValueString(request, "nickname");
			if (StringUtil.isNull(nickname)) {
				result.setMessage("nickname为空！");
				return result;
			}
			
			String iconUrl = getParamValueString(request, "iconUrl");
			if (StringUtil.isNull(iconUrl)) {
				result.setMessage("iconUrl为空！");
				return result;
			}
			
			// 查询是否新用户
			Query query = new Query();
			query.put("USER_ACCOUNT", userAccount);
			List<PubgUser> pubgUserList = pubgUserService.findList(query);
			if (pubgUserList != null && pubgUserList.size() > 1) {
				result.setMessage("帐号存在多个，请联系管理员");
				return result;
			}
			
			PubgUser pubgUser = null;
			if (pubgUserList == null || pubgUserList.isEmpty()) {
				log.info("新账号登录！");
				Integer regFrom = getParamValueInteger(request, "regFrom", 10);
				
				pubgUser = new PubgUser();
				pubgUser.setUserAccount(userAccount);
				pubgUser.setUserRole(UserConstant.USER_ROLE_10.getId());
				pubgUser.setRegFrom(regFrom);
				pubgUser.setRegIp(getIp(request));
				pubgUser.setRegTime(DateUtil.getCurrentDateTime());
				pubgUser.setInfoCompleteFlag(0);
				pubgUser.setBalance(0.0);
				pubgUser.setMatchAmount(0);
				pubgUser.setWinAmount(0);
				pubgUser.setWinSum(0.0);
				pubgUser.setRealNameFlag(0);
				pubgUser.setPhoto(iconUrl);
				pubgUser.setNickname(nickname);
				
				PubgUserLoginBanding pubgUserLoginBanding = new PubgUserLoginBanding();
				pubgUserLoginBanding.setUserName(nickname);
				pubgUserLoginBanding.setThirdType(loginWay);
				pubgUserLoginBanding.setThridId(openId);
				if (loginWay == 20) {
					pubgUser.setRegFrom(30);
					pubgUserLoginBanding.setThirdName("QQ");
				} else if (loginWay == 30) {
					pubgUser.setRegFrom(40);
					pubgUserLoginBanding.setThirdName("微信");
				} else if (loginWay == 40) {
					pubgUser.setRegFrom(50);
					pubgUserLoginBanding.setThirdName("小程序");
				}
				pubgUserLoginBanding.setBandingTime(pubgUser.getRegTime());
				this.pubgUserLoginBandingService.saveObj(pubgUserLoginBanding);
				
				// 插入注册记录
				pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), UserConstant.USER_OPT_TYPE_10.getId().longValue(), UserConstant.USER_OPT_TYPE_10.getName());
			}
			
			if (pubgUser == null) {
				pubgUser = pubgUserList.get(0);
			}
			
			// 查询第三方登陆信息
			PubgUserLoginBanding userBanding = null;
			List<PubgUserLoginBanding> userBandingList = this.pubgUserService.findUserBandingInfo(pubgUser.getRowId(), loginWay);
			if (userBandingList.size() > 1) {
				result.setMessage("openId存在多个，请联系客服！");
				return result;
			}
			if (userBandingList.size() == 1) {
				userBanding = userBandingList.get(0);
			}
			
			// 如果第三方登陆信息不存在，插入一条（老帐号用第三方登陆时）
			if (userBanding == null && !pubgUserList.isEmpty()) {
				userBanding = new PubgUserLoginBanding();
				userBanding.setUserId(pubgUser.getRowId());
				userBanding.setUserName(nickname);
				userBanding.setThirdType(loginWay);
				userBanding.setThridId(openId);
				if (loginWay == 20) {
					userBanding.setThirdName("QQ");
				} else if (loginWay == 30) {
					userBanding.setThirdName("微信");
				} else if (loginWay == 40) {
					userBanding.setThirdName("小程序");
				}
				userBanding.setBandingTime(DateUtil.getCurrentDateTime());
				this.pubgUserLoginBandingService.saveObj(userBanding);
			}
			
			// 验证openId是否正确
			if (!openId.equals(userBanding.getThirdId())) {
				result.setMessage("openId错误！");
				return result;
			}
			
			// 插入登陆记录
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), UserConstant.USER_OPT_TYPE_20.getId().longValue(), UserConstant.USER_OPT_TYPE_20.getName());
			
			// 把登录成功后token保存
			String token = TokenUtil.buildToken();
			tokenHandler.putToken(token, pubgUser.getRowId() + "", pubgUser.getRowId() + "");
			pubgUser.setToken(token);
			
			// 更新验证码状态
			smsService.updateUserPhoneYzmState(null, userAccount, SmsConstant.USER_PHONE_MODEL_TYPE_100);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("token", token);
			data.put("rowId", pubgUser.getRowId());
			data.put("userAccount", pubgUser.getUserAccount().substring(0, 3) + "****" + pubgUser.getUserAccount().substring(8));
			data.put("nickname", pubgUser.getNickname() == null ? "" : pubgUser.getNickname());
			data.put("nicknameInitial", pubgUser.getNicknameInitial() == null ? "" : pubgUser.getNicknameInitial());
			data.put("gameRole", pubgUser.getGameRole() == null ? "" : pubgUser.getGameRole());
			data.put("linkQq", pubgUser.getLinkQq() == null ? "" : pubgUser.getLinkQq());
			data.put("balance", pubgUser.getBalance() == null ? 0 : pubgUser.getBalance());
			data.put("photo", pubgUser.getPhoto() == null ? "" : pubgUser.getPhoto());
			data.put("userRole", pubgUser.getUserRole());
			data.put("infoCompleteFlag", pubgUser.getInfoCompleteFlag() == null ? 0 : pubgUser.getInfoCompleteFlag());
			
			result.setCode(0);
			result.setData(data);
			result.setMessage("登陆成功");
		} catch (Exception e) {
			log.error("***************用户登录出错了", e);
		}
		return result;
	}

    /**
     * 获取微信小程序openId接口
     *
     * @param appid
     * @param secret
     * @param jsCode
     * @return
     */
	@ResponseBody
    @RequestMapping("/getWxSmallCodeOpenId")
    public Result<SmallCodeOpenId> getWxSmallCodeOpenId(HttpServletRequest request, String appid, String secret, String jsCode) {
		Result<SmallCodeOpenId> result = new Result<SmallCodeOpenId>();
		result.setCode(-1);
		result.setMessage("获取微信小程序openId失败！");
        try {
        	result = tokenHandler.getWxSmallCodeOpenId(appid, secret, jsCode);
        } catch (Exception e) {
            log.error("获取微信小程序openId出错！", e);
        }
        return result;
    }


	/**
	 * 小程序解密数据获取手机号
	 *
	 * @param appid
	 * @param sessionKey
	 * @param encryptedData
	 * @param iv
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getWxSmalldDcryptPhone")
	public Result<String> getWxSmallCodeOpenId(HttpServletRequest request, String appid, String sessionKey, String encryptedData , String iv) {
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("获取微信小程序手机号失败！");
		try {
			result = tokenHandler.getWxSmalldDcryptPhone(appid, sessionKey, encryptedData,iv);
		} catch (Exception e) {
			log.error("获取微信小程序手机号出错！", e);
		}
		return result;
	}


    
	/**
	 * 退出
	 * 
	 * @author 朱建文 创建时间：2017年12月20日 下午1:51:23
	 */
	@ResponseBody
	@RequestMapping("/recLogout")
	public String logout(String token, HttpServletRequest request){
		Result<SysStaff> result = new Result<SysStaff>();
		result.setCode(-1);
		result.setMessage("退出登录出错了");
		try {
			SysStaff user = (SysStaff) request.getSession().getAttribute("user");
			tokenHandler.removeSysToken(token, JsonUtil.toJSON(user));
			result.setCode(0);
		} catch (Exception e) {
			log.error("退出出错", e);
		}
		return result.toString();
	}
}
